來最後幾天我們又跳回去React-Testing-Library XDDD
相信還是有很多公司使用redux來當作global store來使用,因此最後幾天我們來聊聊redux如何使用RTL來做單元測試.
那接下來寫一個非常簡單的reducer
const SET_NAME = 'SET_NAME';
const initialState = {
name: ''
};
const reducer = (state = initialState, action) => {
switch (action.type) {
case SET_NAME:
return {
name: 'stan'
}
default:
return state;
}
}
再來一個非常簡單的component
import { useSelector, useDispatch } from 'react-redux';
const Avatar = () => {
const name = useSelector(strate => state.name);
const dispatch = useDispatch();
const handleChangeName = () => dispatch({type: 'SET_NAME' })
return (
<>
<div data-testid="name">
{name}
</div>
<button onClick={handleChangeName}>submit</button>
</>
)
}
再來就是一個簡單的test case
import { render } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { Provider } from 'react-redux';
import store from './store';
import Avatar from '....';
test('render component with redux', () => {
const { getByTestId, getByText } = render(
<Provider store={store}>
<Avatar />
</Provider>
);
const elem = getByText(/submit/i)
userEvent.click(elem);
expect(getByTestId('name')).toHaveTextContent('stan')
})
這樣就可以做一個簡單的redux整體流程的測試,謝謝大家